<template>
  <div class="basic-info-step">
    <div class="step-header">
      <h3>基本信息</h3>
      <p>请填写您的基本个人信息</p>
    </div>

    <el-form 
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="basic-info-form"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="form.gender" placeholder="请选择性别" style="width: 100%">
              <el-option
                v-for="option in GENDER_OPTIONS"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birth_date">
            <el-date-picker
              v-model="form.birth_date"
              type="date"
              placeholder="请选择出生日期"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号码" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="邮箱地址" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱地址" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="居住地址" prop="address">
            <el-input v-model="form.address" placeholder="请输入居住地址" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="求职意向" prop="job_intention">
            <el-input v-model="form.job_intention" placeholder="请输入求职意向" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="期望薪资" prop="expected_salary">
            <el-input v-model="form.expected_salary" placeholder="如：8-12K" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="期望工作地点" prop="work_location">
        <el-input v-model="form.work_location" placeholder="请输入期望工作地点" />
      </el-form-item>

      <el-form-item label="证件照" prop="avatar">
        <div class="id-photo-upload">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :show-file-list="false"
            accept="image/*"
            :on-change="handleAvatarChange"
            :before-upload="beforeAvatarUpload"
            :limit="1"
            :file-list="[]"
          >
            <div class="id-photo-uploader">
              <div v-if="avatarPreviewUrl || form.avatar" class="id-photo-container">
                <img :src="avatarPreviewUrl || form.avatar" class="id-photo" />
                <div class="id-photo-overlay">
                  <el-button type="danger" size="small" @click="clearAvatar" circle>
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
              <div v-else class="id-photo-placeholder">
                <el-icon><Plus /></el-icon>
                <div class="text">上传证件照</div>
                <div class="size-hint">建议尺寸：3.2cm × 2.2cm</div>
              </div>
            </div>
          </el-upload>
          <div class="id-photo-tips">
            <el-text type="info" size="small">
              • 请上传正面免冠证件照<br>
              • 建议尺寸：3.2cm × 2.2cm（约378×260像素）<br>
              • 支持JPG、PNG格式，文件大小不超过2MB
            </el-text>
          </div>
        </div>
      </el-form-item>

      <div class="form-actions">
        <el-button type="primary" @click="handleSave" :loading="saving">
          保存基本信息
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules, type UploadFile } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { basicInfoApi, type BasicInfo, GENDER_OPTIONS } from '@/api/resume'

// Props
interface Props {
  resumeId: number
}

// Emits
interface Emits {
  (e: 'completed', completed: boolean): void
  (e: 'data-saved'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const formRef = ref<FormInstance>()
const uploadRef = ref()

// 表单数据
const form = reactive<BasicInfo>({
  name: '',
  gender: 'male',
  birth_date: '',
  phone: '',
  email: '',
  address: '',
  avatar: '',
  job_intention: '',
  expected_salary: '',
  work_location: ''
})

// 证件照文件和预览URL分开处理
const avatarFile = ref<File | null>(null)
const avatarPreviewUrl = ref<string>('')

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 监听表单变化，判断是否完成
watch(form, () => {
  checkCompletion()
}, { deep: true })

// 检查完成状态
const checkCompletion = () => {
  const required = ['name', 'gender', 'phone', 'email']
  const completed = required.every(field => form[field])
  emit('completed', completed)
}

// 获取基本信息
const fetchBasicInfo = async () => {
  loading.value = true
  try {
    const response = await basicInfoApi.getBasicInfo(props.resumeId)
    const data = response.data || response

    if (data.results && data.results.length > 0) {
      // 如果有数据，使用第一条
      Object.assign(form, data.results[0])
    } else if (data.id) {
      // 如果直接返回对象
      Object.assign(form, data)
    }

    // 清除证件照文件和预览URL，确保使用服务器返回的证件照URL
    avatarFile.value = null
    avatarPreviewUrl.value = ''

  } catch (error) {
    // 如果没有数据，保持默认值
    console.log('暂无基本信息数据')
  } finally {
    loading.value = false
  }
}

// 处理头像变化
const handleAvatarChange = (file: UploadFile) => {
  console.log('证件照文件变化:', file)

  if (file.raw && file.raw instanceof File) {
    // 保存文件对象用于上传
    avatarFile.value = file.raw
    console.log('保存的证件照文件:', avatarFile.value)

    // 创建预览URL
    const reader = new FileReader()
    reader.onload = (e) => {
      avatarPreviewUrl.value = e.target?.result as string
    }
    reader.readAsDataURL(file.raw)
  } else {
    console.error('无效的文件对象:', file)
    ElMessage.error('无效的文件对象')
  }
}

// 头像上传前验证
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB')
    return false
  }
  return true
}

// 清除证件照
const clearAvatar = (e: Event) => {
  e.stopPropagation() // 阻止事件冒泡，避免触发上传
  avatarFile.value = null
  avatarPreviewUrl.value = ''
  form.avatar = ''

  // 清除上传组件的文件列表
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }

  ElMessage.success('证件照已清除')
}

// 保存基本信息
const handleSave = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    saving.value = true

    // 如果有新的证件照文件，需要使用FormData
    if (avatarFile.value && avatarFile.value instanceof File) {
      console.log('使用FormData提交，包含证件照文件:', avatarFile.value)
      const formData = new FormData()

      // 添加基本信息字段
      Object.keys(form).forEach(key => {
        if (key !== 'avatar' && form[key] !== null && form[key] !== undefined && form[key] !== '') {
          formData.append(key, form[key])
        }
      })

      // 添加证件照文件
      formData.append('avatar', avatarFile.value)

      // 调试：打印FormData内容
      console.log('FormData内容:')
      for (let [key, value] of formData.entries()) {
        console.log(key, value)
      }

      if (form.id) {
        // 更新
        await basicInfoApi.updateBasicInfo(props.resumeId, form.id, formData)
      } else {
        // 创建
        await basicInfoApi.saveBasicInfo(props.resumeId, formData)
      }
    } else {
      // 没有新的头像文件，使用普通JSON数据
      const dataToSave = { ...form }

      // 如果avatar字段是URL字符串（已有头像），保留它；如果是空字符串，删除它
      if (dataToSave.avatar === '' || dataToSave.avatar === null || dataToSave.avatar === undefined) {
        delete dataToSave.avatar
      }

      if (form.id) {
        // 更新
        await basicInfoApi.updateBasicInfo(props.resumeId, form.id, dataToSave)
      } else {
        // 创建
        await basicInfoApi.saveBasicInfo(props.resumeId, dataToSave)
      }
    }

    // 只在手动保存时显示成功提示
    ElMessage.success('基本信息保存成功')

    // 清除证件照文件，因为已经保存成功
    avatarFile.value = null
    avatarPreviewUrl.value = ''

    // 重新获取数据
    await fetchBasicInfo()

    // 触发数据保存事件
    emit('data-saved')

  } catch (error) {
    console.error('保存基本信息错误:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 生命周期
onMounted(() => {
  fetchBasicInfo()
})
</script>

<style lang="scss" scoped>
.basic-info-step {
  .step-header {
    margin-bottom: 32px;

    h3 {
      font-size: 24px;
      font-weight: 600;
      color: var(--text-color-primary);
      margin: 0 0 8px 0;
    }

    p {
      color: var(--text-color-secondary);
      margin: 0;
    }
  }

  .basic-info-form {
    max-width: 800px;

    .avatar-uploader {
      width: 120px;
      height: 120px;
      border: 2px dashed var(--border-color-light);
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        border-color: var(--color-primary);
      }

      .avatar {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 6px;
      }

      .avatar-placeholder {
        text-align: center;
        color: var(--text-color-placeholder);

        .el-icon {
          font-size: 32px;
          margin-bottom: 8px;
        }

        .text {
          font-size: 14px;
        }
      }
    }

    .form-actions {
      margin-top: 32px;
      padding-top: 24px;
      border-top: 1px solid var(--border-color-extra-light);
    }
  }
}

// 证件照上传样式
.id-photo-upload {
  .id-photo-uploader {
    .id-photo-container {
      position: relative;
      display: inline-block;

      .id-photo {
        width: 130px;  // 3.2cm ≈ 96px (按3.2:2.2比例)
        height: 189px; // 2.2cm ≈ 66px
        border-radius: 4px;
        object-fit: cover;
        border: 2px solid #dcdfe6;
      }

      .id-photo-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        transition: opacity 0.3s;

        &:hover {
          opacity: 1;
        }
      }
    }

    .id-photo-placeholder {
      width: 130px;  // 3.2cm ≈ 96px
      height: 189px; // 2.2cm ≈ 66px
      border: 2px dashed #dcdfe6;
      border-radius: 4px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: border-color 0.3s;

      &:hover {
        border-color: #409eff;
      }

      .el-icon {
        font-size: 20px;
        color: #8c939d;
        margin-bottom: 4px;
      }

      .text {
        color: #8c939d;
        font-size: 12px;
        text-align: center;
        line-height: 1.2;
      }

      .size-hint {
        color: #a8abb2;
        font-size: 10px;
        margin-top: 2px;
        text-align: center;
      }
    }
  }

  .id-photo-tips {
    margin-top: 8px;
    padding: 8px;
    background: #f5f7fa;
    border-radius: 4px;

    .el-text {
      line-height: 1.4;
    }
  }
}

@media (max-width: 768px) {
  .basic-info-step {
    .basic-info-form {
      .el-row {
        .el-col {
          margin-bottom: 16px;
        }
      }
    }
  }
}
</style>
